package com.web.service;

import com.google.common.collect.Lists;
import com.web.dao.RoleMapper;
import com.web.dao.UserMapper;
import com.web.dao.UserRoleMapper;
import com.web.domain.WebResponse;
import com.web.entity.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 *
 * @author xukk
 * @date 2017/9/6
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RoleMapper roleMapper;

    public WebResponse addUser(User user) {
        user.setPassword(DigestUtils.md5Hex(user.getPassword()));
        user.setAccountNonExpired(true);
        user.setAccountNonLocked(true);
        user.setCredentialsNonExpired(true);
        user.setEnabled(true);
        user.setStatus(1);
        int res = userMapper.insertSelective(user);
        if (res > 0) {
            if (user.getRoles() != null && user.getRoles().size() > 0) {
                List<UserRole> userRoles = Lists.newArrayList();
                user.getRoles().forEach(value -> {
                    UserRole userRole = new UserRole();
                    userRole.setUserId(Long.valueOf(user.getId()));
                    userRole.setRoleId(value.getId());
                    userRoles.add(userRole);
                });
                userRoleMapper.insertAll(userRoles);
            }
            return WebResponse.ok("");
        } else {
            return WebResponse.fail(WebResponse.CF);
        }
    }

    public WebResponse delUser(Long userId) {
        User user = userMapper.selectByPrimaryKey(userId);
        if (user == null) {
            return WebResponse.fail("该对象不存在");
        }
        if (userMapper.deleteByPrimaryKey(userId) > 0) {
            UserRoleExample userRoleExample = new UserRoleExample();
            userRoleExample.createCriteria().andUserIdEqualTo(user.getId());
            userRoleMapper.deleteByExample(userRoleExample);
            return WebResponse.ok("");
        } else {
            return WebResponse.fail(WebResponse.UF);
        }
    }

    public WebResponse updateUser(User user, Long[] roleIds) {
        if (user.getId() == null || user.getId() == 0) {
            return WebResponse.fail("对象不存在");
        }
        UserExample userExample1 = new UserExample();
        userExample1.createCriteria().andIdEqualTo(user.getId());
        userExample1.setPaging(false);
        List<User> userList = userMapper.selectRoleByExample(userExample1);
        if (userList == null || userList.size() == 0) {
            return WebResponse.fail("对象不存在");
        }
        User user1 = userList.get(0);
        String cur_phone = user1.getPhone();
        String cur_username = user1.getUsername();
        UserExample userExample = new UserExample();
        if (StringUtils.isNotBlank(user.getUsername()) && !StringUtils.equals(cur_username, user.getUsername())) {
            userExample.createCriteria().andUsernameEqualTo(user.getUsername());
            List<User> userList1 = userMapper.selectByExample(userExample);
            if (userList1 != null && userList1.size() > 0) {
                return WebResponse.fail("用户名已存在");
            }
        }
        if (StringUtils.isNotBlank(user.getPhone()) && !StringUtils.equals(cur_phone, user.getPhone())) {
            userExample.createCriteria().andPhoneEqualTo(user.getPhone());
            List<User> userList2 = userMapper.selectByExample(userExample);
            if (userList2 != null && userList2.size() > 0) {
                return WebResponse.fail("手机号已存在");
            }
        }
        user1.setUsername(user.getUsername());
        user1.setPhone(user.getPhone());
        user1.setEmail(user.getEmail());
        RoleExample roleExample = new RoleExample();
        roleExample.createCriteria().andIdIn(Lists.newArrayList(roleIds));
        List<Role> roles = roleMapper.selectByExample(roleExample);
        if (!compare(roles, user1.getRoles())) {
            user1.setRoles(roles);
            UserRoleExample userRoleExample = new UserRoleExample();
            userRoleExample.createCriteria().andUserIdEqualTo(user1.getId());
            userRoleMapper.deleteByExample(userRoleExample);
            List<UserRole> userRoles = Lists.newArrayList();
            roles.forEach(value -> {
                UserRole userRole = new UserRole();
                userRole.setUserId(user1.getId());
                userRole.setRoleId(value.getId());
                userRoles.add(userRole);
            });
            userRoleMapper.insertAll(userRoles);
        }
        if (userMapper.updateByPrimaryKey(user1) > 0) {
            return WebResponse.ok("");
        } else {
            return WebResponse.fail(WebResponse.CF);
        }

    }

    public static boolean compare(List<Role> a, List<Role> b) {
        if (a.size() != b.size()) {
            return false;
        }
        Collections.sort(a, new Comparator<Role>() {
            @Override
            public int compare(Role arg0, Role arg1) {
                return arg0.getId().compareTo(arg1.getId());
            }
        });
        Collections.sort(b, new Comparator<Role>() {
            @Override
            public int compare(Role arg0, Role arg1) {
                return arg0.getId().compareTo(arg1.getId());
            }
        });
        for (int i = 0; i < a.size(); i++) {
            if (!a.get(i).getId().equals(b.get(i).getId())) {
                return false;
            }
        }
        return true;
    }
}
